import json

import random
from PIL import Image, ImageDraw, ImageFont
import colorsys

from mv_util import create_video_from_images_and_audio
from song_downloader import download_song,get_song_id,get_song_info
from nlp import translate_lrc_file,split_sentence,parse_timestamp
def generate_distinct_colors(n):
    """生成n个色调均匀分布的颜色"""
    colors = []
    for i in range(n):
        hue = i / n
        saturation = 0.7 + random.random() * 0.3
        lightness = 0.5 + random.random() * 0.3
        rgb = colorsys.hls_to_rgb(hue, lightness, saturation)
        return_color = tuple(int(x * 255) for x in rgb)
        colors.append(return_color)
    return colors
def get_text_dimensions(text, font):
    """获取文本尺寸"""
    if hasattr(font, "getbbox"):  # Pillow 9.0.0 及以上版本
        bbox = font.getbbox(text)
        return bbox[2] - bbox[0], bbox[3] - bbox[1]
    else:  # 较旧版本
        return font.getsize(text)

def create_lyric_image(zh,japanese_words, chinese_words, width=1000, height=400):
    image = Image.new('RGB', (width, height), color='white')
    draw = ImageDraw.Draw(image)

    try:
        japanese_font = ImageFont.truetype("msgothic.ttc", 40)
        chinese_font = ImageFont.truetype("simhei.ttf", 40)
    except IOError:
        japanese_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 40)
        chinese_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 40)

    colors = generate_distinct_colors(len(japanese_words))

    # 绘制日语行
    x_offset = 50
    zh2color  ={}
    for i, word in enumerate(japanese_words):
        color = colors[i % len(colors)]
        draw.text((x_offset, 100), word, font=japanese_font, fill=color)
        word_width, _ = get_text_dimensions(word, japanese_font)
        x_offset += word_width + 10
        w = chinese_words[i]
        zh2color[w] = color

    # 绘制中文行
    x_offset = 50

    chinese_words = [z for z in chinese_words if z in zh and z]
    target_words = split_sentence(zh, chinese_words)

    for i, word in enumerate(target_words):
        if word in zh2color:
            color = zh2color[word]
        else:
            color = (0,0,0)#random.choice(colors)
        draw.text((x_offset, 250), word, font=chinese_font, fill=color)
        word_width, _ = get_text_dimensions(word, chinese_font)
        x_offset += word_width + 10
    # for i, (jp_word, ch_word) in enumerate(zip(japanese_words, chinese_words)):
    #     color = colors[i % len(colors)]
    #     draw.text((x_offset, 250), ch_word, font=chinese_font, fill=color)
    #     word_width, _ = get_text_dimensions(ch_word, chinese_font)
    #     x_offset += word_width + 10
    #
    return image









def process_lyrics_to_images(data):
    """
    image_info = [
    ("lyric_1.png", 0, 5),    # 图片1从0秒开始，显示5秒
    ("lyric_2.png", 5, 10),   # 图片2从5秒开始，显示5秒
    ("lyric_3.png", 10, 15),  # 图片3从10秒开始，显示5秒
    ("lyric_4.png", 15, 20),  #
    ]

    :param data:
    :return image_info:
    """
    images = []
    for index, (t, item) in enumerate(data['data']):
        # 解析时间戳
        current_time = parse_timestamp(t)

        # 计算下一个时间戳（如果是最后一个，则使用一个默认的持续时间，比如5秒）
        next_time = parse_timestamp(data['data'][index + 1][0]) if index + 1 < len(data['data']) else current_time + 5
        print('itme',item)
        if '{' in item and '}' in item:

            sentence = json.loads(item)
            japanese_line = sentence['phrase_split_list']
            if isinstance(japanese_line,list):
                japanese_words = japanese_line
            else:
                japanese_words = japanese_line.split('/') if '/' in japanese_line else [japanese_line]
            print(japanese_words)

            phrase_split2zh = sentence['phrase_split2zh']
            zh = sentence['zh']
            chinese_words = [phrase_split2zh.get(jp_word, "") for jp_word in japanese_words]

            image = create_lyric_image(zh, japanese_words, chinese_words)
            output_path = f'output/lyric_{len(images) + 1}.png'
            image.save(output_path)

            # 添加图片信息到images列表
            images.append((output_path, current_time, next_time))

    return images


def read_json(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data



# 下载mp3 和 lrc
print("开始下载歌曲")
url = "https://music.163.com/song?id=4888333&uct2=U2FsdGVkX19bzrSswVRAFXGWkvJvgmXRjd6MceUSC3g="
song_id = get_song_id(url)
print(f"Song ID: {song_id}")
song_name,audio_path,lrc_path = download_song(song_id)
output_file = f'output/{song_name}.json'
print('开始翻译',lrc_path,output_file)
translate_lrc_file(lrc_path, output_file)

print('【完成】翻译')
data = read_json(output_file)
# r"D:\CloudMusic\doriko,初音ミク\doriko,初音ミク - 夕日坂.mp3"
output_path = f"output/{song_name}.mp4"

print('生成歌词图片')
image_info = process_lyrics_to_images(data)
print('【完成】生成歌词图片')

print('生成视频')
create_video_from_images_and_audio(audio_path, image_info, output_path)
print('【完成】生成视频')

